<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useDatasetStore } from './stores/dataset.js'
import { useConversationStore } from './stores/conversation.js'
import DatasetManager from './components/DatasetManager/DatasetManager.vue'
import ConversationEditor from './components/ConversationEditor/ConversationEditor.vue'
import ToolsPanel from './components/ToolsManager/ToolsPanel.vue'
import { WarningFilled } from '@element-plus/icons-vue'

const datasetStore = useDatasetStore()
const conversationStore = useConversationStore()

// 未保存更改对话框相关数据
const unsavedChangesDialogVisible = ref(false)
const unsavedChangesDialogMessage = ref('')
const unsavedChangesAction = ref('')
const unsavedChangesResolve = ref(null)

// 应用初始化
onMounted(() => {
  // 创建一个空的数据集
  datasetStore.createDataset('新建数据集')
  // 将其标记为未修改状态（因为这是初始状态）
  datasetStore.currentDataset.isModified = false
  conversationStore.selectConversation(-1)
})

// 通用的保存提醒函数
const checkUnsavedChanges = async (actionName) => {
  if (!datasetStore.hasUnsavedChanges) {
    return true // 没有未保存更改，可以继续
  }
  
  return new Promise((resolve) => {
    unsavedChangesAction.value = actionName
    unsavedChangesDialogMessage.value = `当前数据集有未保存的更改，是否要保存？`
    unsavedChangesResolve.value = resolve
    unsavedChangesDialogVisible.value = true
  })
}

// 处理未保存更改对话框的操作
const handleUnsavedChangesAction = async (action) => {
  unsavedChangesDialogVisible.value = false
  
  try {
    if (action === 'save') {
      // 用户选择保存
      if (datasetStore.currentDataset.filePath) {
        // 有文件路径，直接保存
        await datasetStore.saveDataset()
      } else {
        // 没有文件路径，需要选择保存位置
        const { save } = await import('@tauri-apps/plugin-dialog')
        
        const filePath = await save({
          title: '保存当前数据集',
          defaultPath: datasetStore.currentDataset.name + '.json',
          filters: [{
            name: 'JSON 数据集',
            extensions: ['json']
          }]
        })
        
        if (!filePath) {
          // 用户取消了保存，不继续操作
          unsavedChangesResolve.value(false)
          return
        }
        
        await datasetStore.saveDataset(filePath)
      }
      ElMessage.success('数据集已保存')
      unsavedChangesResolve.value(true)
    } else if (action === 'discard') {
      // 用户选择不保存，丢弃更改并继续操作
      datasetStore.currentDataset.isModified = false // 清除未保存状态
      unsavedChangesResolve.value(true)
    } else if (action === 'cancel') {
      // 用户取消操作
      unsavedChangesResolve.value(false)
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(`保存失败: ${error.message}`)
    unsavedChangesResolve.value(false)
  }
}

// 处理对话框关闭（点击X或ESC）
const handleUnsavedChangesDialogClose = () => {
  unsavedChangesDialogVisible.value = false
  unsavedChangesResolve.value(false)
}

// 菜单操作
const handleMenuAction = async (action) => {
  switch (action) {
    case 'new':
      await handleNewDataset()
      break
    case 'open':
      await handleOpenDataset()
      break
    case 'save':
      if (datasetStore.currentDataset.filePath) {
        await handleSaveDataset()
      } else {
        await handleSaveAsDataset()
      }
      break
    case 'validate':
      datasetStore.validateDataset()
      break
    case 'import':
      await handleImportDataset()
      break
    case 'export':
      await handleExportDataset()
      break
    case 'merge':
      await handleMergeDatasets()
      break
    case 'add-conversation':
      datasetStore.addConversation()
      const newIndex = datasetStore.currentDataset.data.length - 1
      conversationStore.selectConversation(newIndex)
      break
  }
}

// 新建数据集处理
const handleNewDataset = async () => {
  try {
    // 检查未保存更改
    const canContinue = await checkUnsavedChanges('新建')
    if (!canContinue) return
    
    // 创建新数据集
    datasetStore.createDataset('新建数据集')
    // 将其标记为未修改状态（新建的空数据集应该是干净的）
    datasetStore.currentDataset.isModified = false
    // 重置对话选择
    conversationStore.selectConversation(-1)
    
    ElMessage.success('已创建新数据集')
  } catch (error) {
    console.error('新建数据集失败:', error)
    ElMessage.error(`新建数据集失败: ${error.message}`)
  }
}

// 打开数据集处理
const handleOpenDataset = async () => {
  try {
    // 检查未保存更改
    const canContinue = await checkUnsavedChanges('打开')
    if (!canContinue) return
    
    const { open } = await import('@tauri-apps/plugin-dialog')
    
    const selectedFile = await open({
      title: '打开数据集文件',
      multiple: false,
      filters: [{
        name: 'JSON 数据集',
        extensions: ['json']
      }]
    })
    
    if (!selectedFile) {
      return
    }
    
    ElMessage.info('正在打开数据集...')
    
    await datasetStore.loadDataset(selectedFile)
    
    // 如果有对话数据，选择第一个
    if (datasetStore.currentDataset.data.length > 0) {
      conversationStore.selectConversation(0)
    } else {
      conversationStore.selectConversation(-1)
    }
    
    ElMessage.success('数据集打开成功')
  } catch (error) {
    console.error('打开数据集失败:', error)
    ElMessage.error(`打开数据集失败: ${error.message}`)
  }
}

// 保存数据集处理
const handleSaveDataset = async () => {
  try {
    ElMessage.info('正在保存数据集...')
    
    await datasetStore.saveDataset()
    
    ElMessage.success('数据集保存成功')
  } catch (error) {
    console.error('保存数据集失败:', error)
    ElMessage.error(`保存数据集失败: ${error.message}`)
  }
}

// 另存为数据集处理
const handleSaveAsDataset = async () => {
  try {
    const { save } = await import('@tauri-apps/plugin-dialog')
    
    const filePath = await save({
      title: '保存数据集文件',
      defaultPath: datasetStore.currentDataset.name + '.json',
      filters: [{
        name: 'JSON 数据集',
        extensions: ['json']
      }]
    })
    
    if (!filePath) {
      return
    }
    
    ElMessage.info('正在保存数据集...')
    
    await datasetStore.saveDataset(filePath)
    
    ElMessage.success('数据集保存成功')
  } catch (error) {
    console.error('保存数据集失败:', error)
    ElMessage.error(`保存数据集失败: ${error.message}`)
  }
}

// 导入数据集处理 (追加到当前数据集)
const handleImportDataset = async () => {
  try {
    // 检查未保存更改
    const canContinue = await checkUnsavedChanges('导入')
    if (!canContinue) return
    
    const { open } = await import('@tauri-apps/plugin-dialog')
    
    const selectedFile = await open({
      title: '导入数据集文件',
      multiple: false,
      filters: [{
        name: 'JSON 数据集',
        extensions: ['json']
      }]
    })
    
    if (!selectedFile) {
      return
    }
    
    ElMessage.info('正在导入数据集...')
    
    const result = await datasetStore.importDataset(selectedFile)
    
    if (result.success) {
      ElMessage.success(result.message)
      // 选择最后一个导入的对话
      if (datasetStore.currentDataset.data.length > 0) {
        conversationStore.selectConversation(datasetStore.currentDataset.data.length - 1)
      }
    }
  } catch (error) {
    console.error('导入数据集失败:', error)
    ElMessage.error(`导入数据集失败: ${error.message}`)
  }
}

// 导出数据集处理
const handleExportDataset = async () => {
  try {
    if (datasetStore.isEmpty) {
      ElMessage.warning('当前数据集为空，无法导出')
      return
    }
    
    const { save } = await import('@tauri-apps/plugin-dialog')
    
    const filePath = await save({
      title: '导出数据集文件',
      defaultPath: `${datasetStore.currentDataset.name}_export.json`,
      filters: [{
        name: 'JSON 数据集',
        extensions: ['json']
      }]
    })
    
    if (!filePath) {
      return
    }
    
    ElMessage.info('正在导出数据集...')
    
    await datasetStore.exportDataset(filePath)
    
    ElMessage.success('数据集导出成功')
  } catch (error) {
    console.error('导出数据集失败:', error)
    ElMessage.error(`导出数据集失败: ${error.message}`)
  }
}

// 合并数据集处理
const handleMergeDatasets = async () => {
  try {
    // 检查未保存更改
    const canContinue = await checkUnsavedChanges('合并')
    if (!canContinue) return
    
    // 使用 Tauri 的文件对话框选择多个文件
    const { invoke } = await import('@tauri-apps/api/core')
    const { open } = await import('@tauri-apps/plugin-dialog')
    
    const selectedFiles = await open({
      title: '选择要合并的数据集文件',
      multiple: true,
      filters: [{
        name: 'JSON 数据集',
        extensions: ['json']
      }]
    })
    
    if (!selectedFiles || selectedFiles.length === 0) {
      return
    }
    
    const filePaths = Array.isArray(selectedFiles) ? selectedFiles : [selectedFiles]
    
    ElMessage.info('正在合并数据集...')
    
    const result = await datasetStore.mergeDatasets(filePaths)
    
    if (result.success) {
      ElMessage.success(result.message)
      // 如果有对话数据，选择第一个
      if (datasetStore.currentDataset.data.length > 0) {
        conversationStore.selectConversation(0)
      }
    }
  } catch (error) {
    console.error('合并数据集失败:', error)
    ElMessage.error(`合并数据集失败: ${error.message}`)
  }
}
</script>

<template>
  <div class="app">
    <!-- 工具栏 -->
    <el-row class="toolbar">
      <el-col :span="12">
        <el-button-group>
          <el-button type="primary" @click="handleNewDataset()">新建</el-button>
          <el-button @click="handleMenuAction('open')">打开</el-button>
          <el-button @click="handleMenuAction('save')" :disabled="!datasetStore.hasUnsavedChanges">保存</el-button>
        </el-button-group>
        
        <el-button-group style="margin-left: 10px;">
          <el-button @click="handleMenuAction('import')">导入</el-button>
          <el-button @click="handleMenuAction('export')">导出</el-button>
          <el-button @click="handleMenuAction('merge')">合并</el-button>
        </el-button-group>
        
        <el-button 
          type="primary" 
          @click="handleMenuAction('validate')"
          style="margin-left: 10px;"
        >
          验证
        </el-button>
      </el-col>
      
      <el-col :span="12" class="toolbar-stats">
        <span v-if="datasetStore.datasetStats">
          数据条数: {{ datasetStore.datasetStats.totalConversations }} | 
          消息总数: {{ datasetStore.datasetStats.totalMessages }} |
          <el-tag v-if="datasetStore.hasUnsavedChanges" type="warning" size="small">
            未保存
          </el-tag>
          <el-tag v-else type="success" size="small">
            已保存
          </el-tag>
        </span>
      </el-col>
    </el-row>

    <!-- 主内容区域 -->
    <el-container class="main-container">
      <!-- 左侧：数据集管理 -->
      <el-aside width="280px" class="left-panel">
        <DatasetManager />
      </el-aside>

      <!-- 中间：对话编辑器 -->
      <el-main class="center-panel">
        <ConversationEditor />
      </el-main>

      <!-- 右侧：工具面板 -->
      <el-aside width="320px" class="right-panel">
        <ToolsPanel />
      </el-aside>
    </el-container>

    <!-- 状态栏 -->
    <div class="status-bar">
      <span>数据集工具 v1.0</span>
    </div>

    <!-- 未保存更改确认对话框 -->
    <el-dialog
      v-model="unsavedChangesDialogVisible"
      title="未保存的更改"
      width="400px"
      :close-on-click-modal="false"
      @close="handleUnsavedChangesDialogClose"
    >
      <div class="unsaved-changes-dialog-content">
        <el-icon class="warning-icon" color="#E6A23C" size="24px">
          <WarningFilled />
        </el-icon>
        <div class="unsaved-changes-message">
          {{ unsavedChangesDialogMessage }}
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer-three">
          <el-button @click="handleUnsavedChangesAction('cancel')" size="default">
            取消
          </el-button>
          <el-button @click="handleUnsavedChangesAction('discard')" type="warning" size="default">
            不保存
          </el-button>
          <el-button @click="handleUnsavedChangesAction('save')" type="primary" size="default">
            保存并{{ unsavedChangesAction }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.app {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.toolbar {
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 8px 16px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.toolbar-stats {
  text-align: right;
  font-size: 12px;
  color: #606266;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.main-container {
  flex: 1;
  min-height: 0;
}

.left-panel {
  background: #ffffff;
  border-right: 1px solid #e4e7ed;
}

.center-panel {
  background: #ffffff;
  padding: 0;
}

.right-panel {
  background: #ffffff;
  border-left: 1px solid #e4e7ed;
}

.status-bar {
  background: #f5f7fa;
  border-top: 1px solid #e4e7ed;
  padding: 4px 16px;
  font-size: 12px;
  color: #909399;
  flex-shrink: 0;
}

.unsaved-changes-dialog-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px 0;
}

.warning-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.unsaved-changes-message {
  flex: 1;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
}

.dialog-footer-three {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>

<style>
/* 全局样式重置 */
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
}

#app {
  height: 100vh;
  overflow: hidden;
}

/* Element Plus 组件样式调整 */
.el-menu--horizontal > .el-sub-menu .el-sub-menu__title {
  border-bottom: none;
}

.el-divider--horizontal {
  margin: 8px 0;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  }

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
  }

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}
</style>
